<?php

class PrePaymentController extends Controller {

    public function filters() {
        return array(
            'accessControl', // perform access control for CRUD operations
            array(
                'application.filters.RequireLoginFilter',
            ),
        );
    }

    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    public function accessRules() {
        return array(
            array('allow', // allow all users to perform 'index' and 'view' actions

                'users' => array('@'),
            ),
            array('deny', // deny all users
                'users' => array('*'),
            ),
        );
    }

    public function actionIndex() {
        outputJsByList(Customers::model()->getActiveList(), 'customerList');
        outputJsByList(PaymentMethods::getList(), 'paymentMethodList');
        outputJsByList(SalesDepartments::getListData(), 'deptList');
        outputJsByList(Jobs::getList(), 'jobList');
        outputJsByList(Coa::model()->getCOAList(), 'accountsList');
        $this->render('index', array(
            'rec' => new Rec(),
            'recleg' => new RecLed
        ));
    }

    public function actionCreate() {
        $data = NULL;
        $finLedgerData = NULL;
        if (isset($_POST['Prepayment']) && isset($_POST['Finledger'])) {
            $data = $_POST['Prepayment'];
            $finLedgerData = $_POST['Finledger'];
        } else {
            echo 'Missing data';
            Yii::app()->end();
        }

        Yii::app()->db->beginTransaction();
        try {
            $invoice = Invoice::model()->findByPk($data['invoice']);
            /* @var $invoice Invoice */
            if ($invoice == NULL) {
                echo 'Invoice failed';
                return;
            }
            $rec = NULL;
            $rec = Rec::model()->find('custno=:custno AND invoice=:invoice', array(
                'custno' => $invoice->custno,
                'invoice' => $invoice->invoice
                    ));
            if ($rec == NULL) {
                $rec = new Rec;
            }
            $amount=$data['amount'];
            $rec->custno = $data['custno'];
            $rec->invoice = $data['invoice'];
            $rec->invdate = $invoice->invoicedate;
            $rec->dept = $data['dept'];
            $rec->period = date('Ym');
            $rec->transid = createRandomUUID();
            $rec->jobnumber = $data['jobnumber'];
            $rec->paid+=$amount;
            $rec->lastpaid = date('Y-m-d H:i:s');
            if ($rec->paid >= $rec->invamt)
                $rec->paidoff = date('Y-m-d H:i:s');
            if( ! $rec->save()){
                echo 'Rec failed';
                return;
            }
            
            $recleg = new RecLed;
            $recleg->custno = $data['custno'];
            $recleg->invoice = $data['invoice'];
            $recleg->paymethod = $data['paymentmethod'];
            $recleg->ckno = $data['ckno'];
            $recleg->amount = $amount;
            $recleg->period = date('Ym');
            $recleg->entryid = createRandomUUID();
            $recleg->depno = $data['dept'];
            $recleg->source = 'R';
            $recleg->debit='1099';
            $recleg->credit='1110';
            $recleg->type='X';
            if( ! $recleg->save() ){
                echo "Recleg failed";
                return;
            }
            
            $log1=new Xlogrec;
            $log1->id=createRandomUUID();
            $log1->transdate=date('Y-m-d');
            $log1->entryid=$recleg->entryid;
            $log1->invoice=$recleg->invoice;
            $log1->amount=$amount;
            $log1->memo='RecRecordPayment: Recorded payment record in RecLed';
            $log1->counter=0;
            $log1->custno=$recleg->custno;
            
            $log2=new Xlogrec;
            $log2->id=createRandomUUID();
            $log2->transdate=date('Y-m-d');
            $log2->entryid=$recleg->entryid;
            $log2->invoice=$recleg->invoice;
            $log2->amount=-$amount;
            $log2->memo='RecRecordPayment: Added line to receivables journal entry';
            $log2->counter=1;
            $log2->custno=$recleg->custno;
            if( $log1->save() && $log2->save()){
                $transcount = 0;
                $transnum = Yii::app()->db->createCommand('select max(cast(trannumber as unsigned)) from tbl_fin_ledger')->queryScalar();
                if ($transnum !== false) {
                    $transnum++;
                } else {
                    $transnum = 0;
                }
                $fin1=new FinLedger;
                $fin1->entryid=createRandomUUID();
                $fin1->transid=$recleg->transid;
                $fin1->trancount=$transcount;
                $fin1->accountid='1099';
                $fin1->amount=-$amount;
                $fin1->source=500;
                $fin1->transdate=$rec->lastpaid;
                $fin1->trannumber=$transnum;
                $fin1->periodid=date('Ym');
                $fin1->transtype=500;
                $fin1->relatedtransid=$fin1->transid;
                
                $fin2=new FinLedger;
                $fin2->entryid=createRandomUUID();
                $fin2->transid=$recleg->transid;
                $fin2->trancount=$transcount;
                $fin2->accountid='1110';
                $fin2->amount=$amount;
                $fin2->source=500;
                $fin2->transdate=$rec->lastpaid;
                $fin2->trannumber=$transnum;
                $fin2->periodid=date('Ym');
                $fin2->transtype=500;
                $fin2->relatedtransid=$fin2->transid;
                
                $fin1->save();
                $fin2->save();
            }
            
            
        } catch (Exception $e) {
            echo $e->getMessage();
            return;
        }


        echo '<h1>data saved</h1>';
    }

    public function actionGetList($page, $order) {
        
    }

}